<template>
  <div :class="className" :style="{height:height,width:width}"></div>
</template>

<script>
  require('echarts/theme/macarons')
  import echarts from 'echarts'
  import { debounce } from '@/utils'

  export default {
    props: {
      className: {
        type: String,
        default: 'chart'
      },
      width: {
        type: String,
        default: '100%'
      },
      height: {
        type: String,
        default: '300px'
      },
      data: {
        type: Array,
        default: []
      }
    },
    data() {
      return {
        chart: null
      }
    },
    mounted() {
      this.initChart()
      this.__resizeHanlder = debounce(() => {
        if (this.chart) {
          this.chart.resize()
        }
      }, 100)
      window.addEventListener('resize', this.__resizeHanlder)
    },
    beforeDestroy() {
      if (!this.chart) {
        return
      }
      window.removeEventListener('resize', this.__resizeHanlder)
      this.chart.dispose()
      this.chart = null
    },
    watch: {
      data: {
        handler(newValue, oldValue) {
          console.log('newValue=', newValue)
          this.data = newValue
          this.chart.setOption({
            legend: {
              left: 'center',
              bottom: '10',
              data: this.data.map(item => item.name)
            },
            series: [
              {
                name: '客户',
                type: 'pie',
                roseType: 'radius',
                radius: [15, 95],
                center: ['50%', '50%'],
                data: this.data,
                animationEasing: 'cubicInOut',
                animationDuration: 2600
              }
            ]
          })
        },
        deep: true
      }
    },
    methods: {
      initChart() {
        this.chart = echarts.init(this.$el, 'macarons')

        this.chart.setOption({
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
            left: 'center',
            bottom: '10',
            data: this.data.map(item => item.name)
          },
          calculable: true,
          series: [
            {
              name: '客户',
              type: 'pie',
              roseType: 'radius',
              radius: [15, 95],
              center: ['50%', '50%'],
              data: this.data,
              animationEasing: 'cubicInOut',
              animationDuration: 2600
            }
          ]
        })
      }
    }
  }
</script>
